package com.etc;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户认证过滤器
 */
@Component
public class UserAuthFilter extends ZuulFilter {
    @Autowired
    private BasicConf basicConf;
    @Override
    public String filterType() { return "pre"; }
    @Override
    public int filterOrder() { return 1; }
    @Override
    public boolean shouldFilter() { return true; }
    @Override
    public Object run() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        String requestURI = currentContext.getRequest().getRequestURI();
        System.out.println("uri-----------"+requestURI);
        //获取白名单
        List<String> apiList = basicConf.getApiList();
        if(apiList.contains(requestURI)){
            return null; //直接返回继续下一个过滤器
        }
        //处理动态参数uri  /{name}/{id}
        for(String wapi:apiList){
            if(wapi.contains("{") && wapi.contains("}") ){ //动态参数
                if(wapi.split("/").length == requestURI.split("/").length){
                    // 将 {}或者{任意字符} 替换成 至少出现一次的任意字符
                    String replaceAll = wapi.replaceAll("\\{.*}", ".{1,}");
                    Pattern compile = Pattern.compile(replaceAll);
                    final Matcher matcher = compile.matcher(requestURI);
                    if(matcher.find())return null;
                }
            }
        }
        //请求不在白名单
        currentContext.setSendZuulResponse(false); //终止请求访问后端接口(其他过滤器还是会走)
        currentContext.setResponseBody("用户不在白名单内,请联系客服");
        //编码设置
        currentContext.getResponse().setContentType("text/html;charset=UTF-8");
        //不再走后面过滤器逻辑
        currentContext.set("isFilter",false); //后面拦截器可以根据这个属性来设置shouldFilter的返回值
        System.out.println("----用户不在白名单");
        return null;
    }
}
